﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using Eacademy.Domain.Abstractions;
using Eacademy.Domain.Models;
using Eacademy.Library.Actions;
using Eacademy.Library.Helpers;
using Eacademy.Library.Membership;
using System.IO;
using Elmah;

namespace Eacademy.Areas.Mentor.Controllers
{
    [CustomAuthorize]
    [ProfileControllerFilter]
    public class LessonsController : Controller
    {
        private const int DefaultPageSize = 10;
        private ISubjectRepository _subjectRepository;
        private IMentorRepository _mentorRepository;
        private ILessonRepository _lessonRepository;

        private string SavePath
        {
            get
            {
                return String.Format(@"{0}", Server.MapPath(AppSettings.FileDirectory));
            }
        }

        public LessonsController(ISubjectRepository subjectRepository, IMentorRepository mentorRepository, ILessonRepository lessonRepository)
        {
            _subjectRepository = subjectRepository;
            _mentorRepository = mentorRepository;
            _lessonRepository = lessonRepository;
        }

        CustomMembershipProvider provider = (CustomMembershipProvider)Membership.Provider;

        //
        // GET: /Mentor/Lessons/
        public ActionResult Index(int id, int? page)
        {
            int currentPageIndex = page.HasValue ? (page.Value <= 0 ? 0 : page.Value - 1) : 0;
            AdminLessonListViewModel adminLessonListViewModel = new AdminLessonListViewModel();
            int totalcount = 0;
            List<AdminLessonsViewModel> lessonList = _lessonRepository.GetLessonsBySubjectId(id, (int)provider.User.UserId, currentPageIndex + 1, DefaultPageSize, out totalcount);
            adminLessonListViewModel.LessonsList = lessonList.ToPagedList(currentPageIndex, DefaultPageSize, totalcount);
            adminLessonListViewModel.Subject = _subjectRepository.GetSubjectBySubjectId(id);
            return View(adminLessonListViewModel);
        }


        public ActionResult Add(int id)
        {
            AdminLessonsViewModel adminLessonsViewModel = new AdminLessonsViewModel();
            adminLessonsViewModel.SubjectId = id;
            return View(adminLessonsViewModel);
        }

        [HttpPost]
        public ActionResult Add(AdminLessonsViewModel adminLessonsViewModel, string filenames)
        {

            UpdateUserUploadedFiles(filenames);
            adminLessonsViewModel.Files = filenames;
            if (_lessonRepository.AddLesson(adminLessonsViewModel, adminLessonsViewModel.SubjectId, (int)provider.User.UserId))
            {
                this.FlashDone("The lesson has been created successfully");
                return Redirect(String.Format("/mentor/lessons/list/{0}", adminLessonsViewModel.SubjectId));
            }
            return View(adminLessonsViewModel);
        }

        public ActionResult Edit(int id)
        {
            AdminLessonsViewModel lesson = _lessonRepository.GetLessonByLessonId(id);
            lesson.FileList = new List<string>(lesson.Files.Split(','));
            return View(lesson);
        }

        [HttpPost]
        public ActionResult Edit(AdminLessonsViewModel adminLessonsViewModel, string filenames, string deletefiles)
        {

            UpdateUserUploadedFiles(filenames, deletefiles);
            adminLessonsViewModel.Files = filenames;
            if (_lessonRepository.UpdateLesson(adminLessonsViewModel))
            {
                this.FlashDone("The lesson has been updated");
            }
            else
            {
                this.FlashError("There was an error updating the lesson");
            }
            return Redirect(String.Format("/mentor/lessons/list/{0}", adminLessonsViewModel.SubjectId));
        }

        [HttpPost]
        public ActionResult Delete(int id)
        {
            if (_lessonRepository.DeleteLesson(id))
            {
                this.FlashDone("The lesson under this subject has been deleted successfully");
            }
            else
            {
                this.FlashError("There was an error deleting the lesson");
            }
            return Content("lesson Delete");
        }

        public ActionResult Details(int id, int lid)
        {
            AdminLessonsViewModel adminLessonsViewModel = _lessonRepository.GetLessonByLessonId(id);
            adminLessonsViewModel.SubjectId = lid;

            return View(adminLessonsViewModel);
        }

        [HttpPost]
        public ActionResult Upload(HttpPostedFileBase file)
        {
            string savePath = SavePath;

            string relaveFilePath = AppSettings.FileDirectory.Replace("~", "");


            if (Directory.Exists(savePath) == false)
            {
                Directory.CreateDirectory(savePath);
            }


            string fileExt = Path.GetExtension(file.FileName).ToLower();
            string fileWoExt = file.FileName;
            string fileName = string.Format("{0}", fileWoExt);

            var fileExtensions = new String[]{
               ".doc",".docx",".txt",".ppt",".pdf",".jpg",".jpeg",".png",".gif"
            };

            if (fileName != string.Empty)
            {
                try
                {
                    if (fileExtensions.ToList().Contains(fileExt))
                    {
                        if (System.IO.File.Exists(savePath + fileName) == true)
                        {
                            System.IO.File.Delete(savePath + fileName);
                        }

                        fileName = string.Format("{0}_-{1}", provider.User.Identification, fileName);

                        string pathfilename = savePath + fileName;
                        file.SaveAs(pathfilename);

                    }
                    else
                    {
                        throw new InvalidDataException("The file is not supported");
                    }
                }
                catch (Exception ex)
                {
                    ErrorSignal.FromCurrentContext().Raise(ex);
                }
            }
            return Content("file uploaded");
        }


        [NonAction]
        private void UpdateUserUploadedFiles(string filenames)
        {
            string savePath = SavePath;

            string[] filenameArray = filenames.Split(',');
            var filenameList = new List<string>(filenameArray);

            foreach (string filename in filenameList)
            {
                string file = String.Format("{0}_-{1}", provider.User.Identification, filename);
                string newFileName = String.Format("{0}_-{1}", provider.User.UserId, filename);
                System.IO.File.Copy(Path.Combine(savePath, file), Path.Combine(savePath, newFileName), true);
            }

            String[] userUploadedDocs = Directory.GetFiles(savePath, provider.User.Identification + "_-*");

            //Delete other files with identification on it

            foreach (String file in userUploadedDocs)
            {
                System.IO.File.Delete(file);
            }

        }

        [NonAction]
        private void UpdateUserUploadedFiles(string filenames, string deletefiles)
        {
            string savePath = SavePath;

            string[] filenameArray = filenames.Split(',');
            var filenameList = new List<string>(filenameArray);

            foreach (string filename in filenameList)
            {
                string file = String.Format("{0}_-{1}", provider.User.Identification, filename);
                string newFileName = String.Format("{0}_-{1}", provider.User.UserId, filename);
                if (System.IO.File.Exists(String.Format("{0}{1}", savePath, file)))
                {
                    System.IO.File.Copy(Path.Combine(savePath, file), Path.Combine(savePath, newFileName), true);
                }
            }

            String[] userUploadedDocs = Directory.GetFiles(savePath, provider.User.Identification + "_-*");

            //Delete other files with identification on it

            foreach (String file in userUploadedDocs)
            {
                System.IO.File.Delete(file);
            }

            string[] deleteFileArray = deletefiles.Split(',');
            var deleteFileList = new List<string>(deleteFileArray);

            foreach (string deleteFile in deleteFileList)
            {
                string file = String.Format("{0}_-{1}", provider.User.UserId, deleteFile.Trim());
                string deletefile = Path.Combine(savePath, file);
                System.IO.File.Delete(deletefile);
            }

        }
    }
}
